import service from './service'
import { CONTENT_TYPE } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { ElLoading } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { Base64 } from 'js-base64'

const { t } = useI18n()
const request = (option: AxiosConfig, loading?) => {
  const { url, method, params, data, headers, responseType, convert } = option

  const userStore = useUserStoreWithOut()

  const localeStore = useLocaleStoreWithOut()

  const _headers = {
    'Content-Type': CONTENT_TYPE,
    [userStore.getTokenKey ?? 'Authorization']: userStore.getToken ?? '',
    'Bmps-Inter-language': localeStore.getCurrentLocale.lang ?? 'zh-CN',
    ...headers
  }

  if (convert) {
    const bpmsConvertConfig = Base64.encode(JSON.stringify(convert))
    _headers['Bmps-Convert-Config'] = bpmsConvertConfig
  }

  return service.request(
    {
      url: url,
      method,
      params,
      data: data,
      responseType: responseType,
      headers: _headers
    },
    loading
  )
}

export default {
  get: <T = any>(option: AxiosConfig, loading?) => {
    return request({ method: 'get', ...option }, loading) as Promise<IResponse<T>>
  },
  post: <T = any>(option: AxiosConfig, loading?) => {
    return request({ method: 'post', ...option }, loading) as Promise<IResponse<T>>
  },
  delete: <T = any>(option: AxiosConfig, loading?) => {
    const deleteLoading =
      loading ||
      ElLoading.service({
        lock: true,
        text: t('common.deleteMessage'),
        background: 'rgba(0, 0, 0, 0.7)'
      })
    return request({ method: 'delete', ...option }, deleteLoading) as Promise<IResponse<T>>
  },
  put: <T = any>(option: AxiosConfig, loading?) => {
    return request({ method: 'put', ...option }, loading) as Promise<IResponse<T>>
  },
  cancelRequest: (url: string | string[]) => {
    return service.cancelRequest(url)
  },
  cancelAllRequest: () => {
    return service.cancelAllRequest()
  }
}
